package com.myjar.excel.v2;

import com.myjar.excel.annotation.ExcelField;
import com.myjar.excel.util.IdentityHashMap;
import com.myjar.excel.util.TypeUtils;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;

public class SortedBeanParser implements BeanParser {

    private static final IdentityHashMap<Class, Set<Field>> cache = new IdentityHashMap<>();

    @Override
    public Set<Field> parse(Class<?> clazz) {
        Set<Field> fields = cache.get(clazz);
        if (fields != null)
            return fields;

        fields =
                new TreeSet<>(
                        (f, fs) -> {
                            ExcelField field = f.getAnnotation(ExcelField.class);
                            ExcelField field1 = fs.getAnnotation(ExcelField.class);
                            return Integer.compare(field.order(), field1.order());
                        }
                );
        TypeUtils.getAllField(clazz, ExcelField.class, fields);
        cache.put(clazz, fields);
        return fields;
    }


}
